Cuestionario Ampliado del Censo de Población y Vivienda 2020

El cuestionario ampliado se guarda en un un archivo .RData.

data <- read_sav("~/Personas_Censo 2020.SAV")

save(data, 
      file = paste0(here::here(), "/Bases/Censo_Personas_2020.RData"))

Se seleccionan las variables que se desean conservar para la realización de este documento y se guarda en un archivo .RData para practicidad del manejo de datos.

load(paste0(here::here(), "/Bases/Censo_Personas_2020.RData"))

mydata <- data %>%
           select(CVE_ENT, ENT, MUN, CVE_MUN, ENT_PAIS_RES_5A, MUN_RES_5A, CVE_MUN_RES15, 
                  ENT_PAIS_NAC, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,  
                  ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI, EDAD, SEXO, AFRODES, HLENGUA, QDIALECT_INALI, 
                  PERTE_INDIGENA, ALFABET, CAUSA_MIG, SITUA_CONYUGAL, HIJOS_NAC_VIVOS, 
                  CONACT, OCUPACION_C, SITTRA, VACACIONES, SERVICIO_MEDICO, INCAP_SUELDO, INGTRMEN, 
                  ACTIVIDADES_C, TIE_TRASLADO_TRAB, MED_TRASLADO_TRAB1, MED_TRASLADO_TRAB2, MED_TRASLADO_TRAB3,
                  ASISTEN, NIVACAD, ESCOLARI, ESCOACUM,  NOMCAR_C, TIE_TRASLADO_ESCU, 
                  MED_TRASLADO_ESC1, MED_TRASLADO_ESC2, MED_TRASLADO_ESC3,
                  FACTOR, ESTRATO, UPM) 

Zonas Metropolitanas 2020

Se anexa la base de datos de las Zonas Metropolitanas 2020 a la base orginal

ZM_2020 <- read.xlsx(paste0(here::here(), "/Bases/Municipio/ZM_2020.xlsx"), 
                      startRow = 7, 
                       skipEmptyRows = TRUE) %>%
            select(CVE_ZM, NOM_ZM, CVE_ENT, NOM_ENT, CVE_MUN, NOM_MUN, MC, CF) %>%
             mutate(CVE_ENT = stringr::str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"),
                    CVE_MUN = stringr::str_pad(.$CVE_MUN, width = 6, side = c("left"), pad = "0"))

Se asignan las claves de las zonas metropolitanas de acuerdo a las diferentes variables de interes: - Residencia hace 5 años - Laboral - Estudiantil - Nacimiento

mydata <- mydata %>%
          # Zonas Metropolitanas por residenicia
           left_join(., ZM_2020 %>% select(-CVE_ENT), by = c("CVE_MUN")) %>%
           # Zonas Metropolitanas en el lugar de residencia hace 5 años
            left_join(., ZM_2020 %>% select(-CVE_ENT, -NOM_ENT, -NOM_MUN) %>% 
                          rename("CVE_ZM_RES15" = "CVE_ZM",
                                 "ZM_RES15" = "NOM_ZM",
                                 "MC_RES15" = "MC",
                                 "CF_RES15" = "CF"), by = c("CVE_MUN_RES15" = "CVE_MUN")) %>%
            # Zonas Metropolitanas en el lugar de trabajo
             left_join(., ZM_2020 %>% select(-CVE_ENT, -NOM_ENT, -NOM_MUN) %>%
                           rename("CVE_ZM_ASI" = "CVE_ZM",
                                  "ZM_ASI" = "NOM_ZM",
                                  "MC_TRABAJO" = "MC",
                                  "CF_TRABAJO" = "CF"), by = c("CVE_MUN_ASI" = "CVE_MUN")) %>%
             # Zonas Metropolitanas en el lugar de estudio
              left_join(., ZM_2020 %>% select(-CVE_ENT, -NOM_ENT, -NOM_MUN) %>%
                            rename("CVE_ZM_ASI" = "CVE_ZM",
                                   "ZM_ASI" = "NOM_ZM",
                                   "MC_ASI" = "MC",
                                   "CF_ASI" = "CF"), by = c("CVE_MUN_ASI" = "CVE_MUN"))

save(mydata, file = paste0(here::here(), "/Bases/06_Migracion por Zonas Metropolitanas_2020.RData"))          

✔️A partir de aquí se pueden correr los códidos 👇. Se carga el archivo Migracion por Zonas Metropolitanas_2020.RData.

load(file = paste0(here::here(), "/Bases/06_Migracion por Zonas Metropolitanas_2020.RData"))

# Para fines prácticos se genera un ponderador de uno 
mydata <- mydata %>%
           select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN,ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI, 
                  EDAD, CONACT, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
            mutate(M = 1) 

# Se vuelve a cargar la base de datos para fines practicos
ZM_2020 <- read.xlsx(paste0(here::here(), "/Bases/Municipio/ZM_2020.xlsx"), 
                      startRow = 7, 
                       skipEmptyRows = TRUE) %>%
            mutate(CVE_ENT = stringr::str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"),
                   CVE_MUN = stringr::str_pad(.$CVE_MUN, width = 6, side = c("left"), pad = "0"))

Entidades y Municipios

Se genera un vector con el nombre de las entidades llamado estados para facilitar los filtros en el documento.
Se genera un vector con las abreviaturas de las entidades llamado ent para fines prácticos.
Se genera un vector con las claves de los municipios, pero es importante hacer notar que tres municipios no entraron el muestreo del Cuestionario Ampliado.

# Claves de los estados
estados <- sjlabelled::get_labels(mydata$CVE_ENT)
nom_estados <- c( "Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila de Zaragoza", "Colima", 
                  "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",        
                  "México", "Michoacán de Ocampo", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
                  "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
                  "Veracruz de Ignacio de la Llave", "Yucatán", "Zacatecas")
est <- c("AGS", "BC", "BCS", "CAMP", "COAH", "COL", "CHIS", "CHIH", "CDMX", "DGO", "GTO", "GRO", "HGO",
         "JAL", "MEX", "MICH", "MOR", "NAY", "NL", "OAX", "PUE", "QRO", "QROO", "SLP","SIN","SON", "TAB", 
         "TAMS", "TLX", "VER", "YUC", "ZAC")

# Claves de los municipios
MUN <- readRDS(paste0(here::here(), "/Bases/municipios_2020.RDS"))
nom_municipios <- sjlabelled::get_labels(MUN$NOM_MUN) %>% as.factor()
municipios <- sjlabelled::get_labels(MUN$CVE_MUN) %>% as.factor()
#saveRDS(MUN, file = paste0(here::here(), "/Bases/municipios_2020.RDS"))

# Claves de las zonas metropolitanas
zm <- sjlabelled::get_labels(mydata$CVE_ZM)[-2]
nom_zm <- sjlabelled::get_labels(mydata$NOM_ZM)[-2]

Movilidad estudiantil

Movilidad interna

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2020 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios) %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

table(MC$I_ZM)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_municipal.RDS"))

Matrices

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_municipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 17)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intramunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil hace 5 años a nivel municipal, 2015 - 2020

Matriz de movilidad estudiantil por zonas metropolitanas
Nivel municipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 002006 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007
001001 274602 37 0 0 1366 122 101 12 0 240 579 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 662 13095 0 0 0 22 272 0 0 67 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 509 0 13315 0 0 0 0 0 0 21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 128 3 0 4370 2 24 319 0 0 3 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 7139 36 45 0 29323 121 88 0 0 11 275 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 706 0 24 0 96 11641 510 95 10 0 163 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 559 0 0 32 9 312 15896 8 22 0 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 74 0 0 0 0 70 38 2489 0 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 158 27 4 0 0 173 264 0 5605 3 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 176 0 0 0 0 0 0 0 0 5129 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2162 3 0 0 431 233 196 0 0 5 14930 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 112987 148 0 262 80 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 16 266099 76 42 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 40 119 24958 1035 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 251 81 1979 459410 1321 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 80 25 78 1909 27084 0 0 0 0 0 0 0 0 0 0 0 0 0
002006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28950 0 0 0 0 0 0 0 0 0 0 0 0
003001 8 0 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 19295 0 43 0 7 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 260 13 0 0 0 0 0 14139 31 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 40 0 0 0 0 0 0 0 75849 146 20 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 55 0 0 0 0 284 92491 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 8 0 4461 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15975 298 36 23 195 18 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 102 79728 0 38 37 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 65 64557 11 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 343 37 21417 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 366 489 5 0 7948 14 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 263 0 0 0 9290 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 11 0 0 0 2252
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 37 227 2 0 44 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 0) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2020 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value < 0) %>% 
#### Filtro de estados <<<<< filter(value >= 100000000000) %>% 
#p <- data.frame(ZM = ZM_CF,
#                filtro_municipio = tabla_municipios,
#                filtro_estado = tabla_estados)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel municipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
################################################################################
tabla1 <- lapply(1:length(ZM_CF), function(x){
                                    # filtro de municipios de la ZM
                                      filtro  <- Inmigrantes[[x]] %>%
                                                  full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                                    mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                                     filter(value > filtro_mig[x]) %>%   ## Cambia el filtro de los municipios de la Zonas Metropolitanas
                                                      pull(rn)
                                      
                                    # filtro de estados
                                     filtro_est <- Inmigrantes[[x]] %>%
                                                    full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                                     filter(rn %nin% ZM[[x]]) %>%
                                                      mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                                       mutate(rn = substr(.$rn, 1, 3)) %>%
                                                        group_by(rn) %>%
                                                         summarise(value = sum(value)) %>%
                                                          filter(value >= filtro_out[x]) %>% 
                                                           pull(rn)
                                     
                                     Migrantes %>%
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "rn") %>% 
                                        melt(., id.vars = "rn", variable.name = "cn") %>%
                                         mutate_if(is.factor, as.character) %>%
                                          filter(.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]) %>%
                                           mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]), value, 0)) %>% 
                                            mutate(rn = case_when(.$rn %in% ZM[[x]] & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                                                  .$rn %in% ZM[[x]] & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZM"), 100),
                                                                  .$rn %nin% ZM[[x]] & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 100),
                                                                  .$rn %nin% ZM[[x]] & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                                                   cn = case_when(.$cn %in% ZM[[x]] & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                                                  .$cn %in% ZM[[x]] & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZM"), 100),
                                                                  .$cn %nin% ZM[[x]] & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 100),
                                                                  .$cn %nin% ZM[[x]] & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                                            filter(value > 0) %>%
                                             dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                              column_to_rownames(., var = "rn") 
  }
)

## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:length(ZM_CF), function(i){
#                                           tabla1[[i]] %>%
#                                            as.data.frame() %>%
#                                             adorn_totals(c("row", "col"), 
#                                                           fill = "-", 
#                                                            na.rm = TRUE, 
#                                                             ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                              select(`Otros estados`) %>%
#                                               slice(nrow(.)) %>%
#                                                mutate(`Otros estados` = .$`Otros estados`/4) %>%
#                                                 pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                              p <- tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      slice(-nrow(.))
#                              if(sum(p) == 0) {
#                                return(0)
#                              } else {
#                                p %>% 
#                                 adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/50) %>%
#                                                    pull(Total)
#                              }
 #                                          
#})

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel municipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel municipal.RDS"))

total_tablas <- totales(tabla1, ZM)
porcentajes_tablas <- porcentajes(tabla1, ZM)

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, totales[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel municipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel municipal.RDS"))

#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1, ZM_CF = ZM_CF, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (municipal).pdf"
 
## Gráficos a nivel municipal 
chord_diagram_graph(file = file, 
                    width = 15,
                    height = 10,
                    family = "Montserrat Medium",
                    paleta = paleta,
                    ZM_CF = ZM_CF,
                    tabla1,
                    tabla2,
                    color_labels = "#000C7D",
                    margin = c(0, 0, 0, 0))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZM a nivel municipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     ZM_CF , 
                     tabla1, 
                     NOM_ZM_CF)

Gráfico Sankey

## Tomamos las Zonas Metropolitanas con más de 3 municipios con flujos migratorios 
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 2) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") 

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                   ZM <- ZM_2020 %>%
                                          select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                           filter(CVE_ZM %in% ZM_CF[x])  %>%
                                            mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                             pull(NOM_MUN)
                                    tabla %>%
                                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                                      filter(value > 0) 
  }
)
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 9, family = "montserrat"),
                                   legend.position = c(1, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.35)) +
                        scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst desagregado por ZM_Absolutos (municipal).pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 18000) %>% 
               pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value >= 6000) %>% 
                      pull(rn)

################################################################################
tabla1 <- Migrantes %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
              filter(.$rn %in% ZM | .$cn %in% ZM) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM| .$cn %in% ZM), value, 0)) %>% 
                mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                      .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZMVM"), 50),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 50),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                       cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                      .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZMVM"), 50),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 50),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                 filter(value > 0) %>%
                  dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                   column_to_rownames(., var = "rn") 
# Paleta de colores
groupColors <- paste0(rev(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1)))))), "7F")

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM (municipal).pdf"),  
          width = 7, height = 7, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)

circos.clear()
circos.par(start.degree = 90, 
           clock.wise = TRUE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(1.5, 4))

# Paleta de colores
groupColors <- setNames(rev(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1)))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 0.2, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(7),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(5),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

dev.off()
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 18000) %>% 
               pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value >= 6000) %>% 
                      pull(rn)

################################################################################
tabla <- Migrantes %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
              filter(.$rn %in% ZM | .$cn %in% ZM) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM| .$cn %in% ZM), value, 0)) %>% 
                mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                      .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(substr(estados[as.numeric(substr(.$rn, 1, 3))], 2, 3), "ZMVM"), 100),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 100),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                       cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                      .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(substr(estados[as.numeric(substr(.$cn, 1, 3))], 2, 3), "ZMVM"), 100),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 100),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                 filter(value > 0)  


tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 


# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()

# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

# Grupo 4
grupo4 <- tabla %>%
           filter(substr(.$rn, 1, 2) %nin% c("09", "15", "13")) %>%
            pull(rn) %>%
             unique()

tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
          ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst de ZMVM a nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
# Paleta de colores
groupColors <- paste0(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))), "7F")

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM_grupos (municipal).pdf"),
          width = 10, height = 10, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)

circos.clear()
circos.par(start.degree = 90, 
           clock.wise = TRUE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(0, 4))

# Paleta de colores
groupColors <- setNames(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 1, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(9),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(7),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

highlight.sector(grupo1, 
                 track.index = 1, 
                 col = groupColors[1], 
                 text = "Ciudad de México", 
                 cex = 1.5, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), niceFacing = TRUE)

highlight.sector(grupo2, 
                 track.index = 1, 
                 col = groupColors[15], 
                 text = "México", 
                 cex = 1.5, 
                 text.col = "white",
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

highlight.sector(grupo3, 
                 track.index = 1, 
                 col = groupColors[20], 
                 text = "Hidalgo", 
                 cex = 1, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

highlight.sector(grupo4, 
                 track.index = 1, 
                 col = groupColors[30], 
                 text = "Otro municipios", 
                 cex = 1.5, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

dev.off()
paleta[1]
etiquetas  <- lapply(1, function(x){
                        orden <- str_sort(unique(c(colnames(tabla1), rownames(tabla1))), numeric = TRUE)
                        p <-  tabla1 %>% 
                               as.data.frame() %>%
                                tibble::rownames_to_column(var = "rn") %>%
                                 melt(., id.vars = "rn", variable.name = "cn") %>%
                                  as.data.frame() %>% 
                                   mutate(rn = str_wrap(.$rn, 100),
                                          cn = str_wrap(.$cn, 100)) %>%
                                    ggplot() + 
                                     geom_bar(aes(x = as.character(value, orden), fill = rn))  + 
                                      geom_bar(aes(x = as.character(value, orden), fill = cn))  + 
                                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                                             text = element_text(family = "Montserrat Medium"),
                                             axis.text = element_blank(),
                                             axis.title = element_blank(),
                                             strip.text = element_text(size = 9, face = "bold", family = "Montserrat Medium"),  
                                             legend.key.size = unit(0.4, "cm"), 
                                             legend.spacing.y = unit(0.4, "cm"),
                                             legend.text = element_text(size = 7, family = "Montserrat Medium"),
                                             legend.title = element_text(size = 8 , family = "Montserrat Medium")) + 
                                       scale_fill_manual(values = colorRampPalette(paleta)(max(ncol(tabla1), nrow(tabla1)))) + 
                                         guides(fill = guide_legend(ncol = 1)) + 
                                        guides(fill = guide_legend(ncol = 1)) + 
                                         labs(fill = "ZM del Valle de México",
                                          color = "ZM del Valle de México")
                         leg <- get_legend(p)
                         as_ggplot(leg)
 })

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZMVM a nivel municipal.pdf"), 
          width = 7, height = 8, 
          fallback_resolution = 400,
          family = "montserrat", onefile = TRUE)
for(i in 1){
  print(etiquetas[i])
}
dev.off()
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                      group_by(rn) %>% 
                       summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(value < 30000) %>% 
               pull(rn)
#########################################################################################

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = ifelse(.$rn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 50), .$rn),
                      cn = ifelse(.$cn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 50) , .$cn)) %>%
                filter(value > 0) 

p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.7,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst de la ZMVM (municipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar 
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (municipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (municipal).RData"))
Indicadores de Movilidad estudiantil
Zonas Metropolitanas
Clave del municipio Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 901 262 274 602 3 139 16 133 −12 994 19 272 0.68 3.494 −2.8 −32 266
001002 51 474 48 275 13 095 1 173 493 680 1 666 4.70 1.977 2.7 −986
001003 58 155 55 019 13 315 567 119 448 686 2.00 0.421 1.6 −238
001004 16 997 15 959 4 370 516 209 307 725 6.26 2.537 3.7 −418
001005 129 859 122 544 29 323 7 830 1 915 5 915 9 745 12.41 3.035 9.4 −3 830
001006 47 557 44 893 11 641 1 630 1 084 546 2 714 7.05 4.690 2.4 −2 168
001007 57 269 53 484 15 896 990 2 295 −1 305 3 285 3.58 8.289 −4.7 −4 590
001008 9 552 8 868 2 489 196 118 78 314 4.26 2.562 1.7 −236
001009 22 461 21 182 5 605 644 35 609 679 5.90 0.321 5.6 −70
001010 20 382 18 987 5 129 193 465 −272 658 1.96 4.725 −2.8 −930
001011 61 986 57 999 14 930 3 075 1 061 2 014 4 136 10.25 3.537 6.7 −2 122
002001 440 624 422 238 112 987 638 857 −219 1 495 0.30 0.397 −0.1 −1 714
002002 1 042 395 1 004 592 266 099 596 870 −274 1 466 0.12 0.170 −0.1 −1 740
002003 102 896 98 206 24 958 1 260 2 136 −876 3 396 2.51 4.249 −1.7 −4 272
002004 1 910 568 1 829 472 459 410 4 038 3 468 570 7 506 0.43 0.371 0.1 −6 936
002005 126 264 121 701 27 084 2 092 1 401 691 3 493 3.37 2.260 1.1 −2 802
002006 117 050 109 811 28 950 0 0 0 0 0.00 0.000 0.0 0
003001 72 358 69 371 19 295 75 5 70 80 0.21 0.014 0.2 −10
003002 62 884 59 781 14 139 316 7 309 323 1.03 0.023 1.0 −14
003003 290 063 279 213 75 849 462 495 −33 957 0.32 0.348 0.0 −990
Fuente: Estimaciones del CONAPO.

Movilidad intramunicipal

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2020 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios & .$I_ZM %in% "Pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_intramunicipal.RDS"))

Matrices

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_intramunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 17)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intramunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil hace 5 años a nivel municipal, 2015 - 2020

Matriz de movilidad estudiantil por zonas metropolitanas
Nivel intramunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 002006 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007
001001 274602 0 0 0 1366 0 0 0 0 0 579 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 0 13095 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 0 0 13315 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 0 0 0 4370 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 7139 0 0 0 29323 0 0 0 0 0 275 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 0 0 0 0 0 11641 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 0 0 0 0 0 0 15896 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 0 0 0 0 0 0 0 2489 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 0 0 0 0 0 0 0 0 5605 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 0 0 0 0 0 0 0 0 0 5129 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2162 0 0 0 431 0 0 0 0 0 14930 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 112987 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 0 266099 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 0 0 24958 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 459410 1321 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1909 27084 0 0 0 0 0 0 0 0 0 0 0 0 0
002006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28950 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19295 0 0 0 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 14139 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 75849 0 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 92491 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4461 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15975 0 0 0 0 0 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 79728 0 0 0 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64557 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 21417 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7948 0 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9290 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2252
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Fuente: Estimaciones del CONAPO.

Matrices por zonas metropolitanas

MR <- NULL
for(i in 1:length(zm)){
tabla <- ZM_2020 %>%
          select(CVE_ZM, CVE_MUN) %>%
           filter(CVE_ZM %in% zm[i]) %>%
            pull(CVE_MUN)

MR[[paste0(zm[i])]] <- Migrantes %>%
                        as.data.frame() %>%
                         tibble::rownames_to_column(var = "CVE_MUN") %>%
                          mutate_if(is.numeric, as.numeric) %>%
                           select(CVE_MUN, all_of(tabla)) %>%
                            filter(CVE_MUN %in% tabla)
}

# Se guardan en un objeto de R 
saveRDS(MR, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matrices de MEst a nivel intramunicipal por ZM2020.RDS"))

# Se genera un Excel con todas las matrices por ZM
wb <- createWorkbook()
for(i in 1:length(zm)){
addWorksheet(wb, paste0(zm[i]))
writeData(wb, i, MR[[paste0(zm[i])]] %>% as.data.frame())
saveWorkbook(wb, 
              file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matrices de MEst a nivel intramunicipal por ZM2020.xlsx"), 
               overwrite = TRUE)
}

Matriz de Movilidad estudiantil en la Zona Metropolitana de Cuernavaca, 2015 - 2020

Matriz de Movilidad estudiantil a nivel intramunicipal
Zona Metropolitana de Cuernavaca
CVE_MUN 017007 017008 017009 017011 017018 017020 017028 017029 017034 017035
017007 89612 911 142 1671 1816 170 0 30 0 72
017008 5262 19610 0 2251 986 0 411 79 0 25
017009 1965 12 4315 20 15 7 0 0 0 0
017011 10197 27 0 43035 459 27 16 470 0 0
017018 4542 558 0 241 24522 0 57 0 0 56
017020 2150 50 8 1585 0 8083 0 812 0 0
017028 1641 276 0 79 1535 5 12603 15 0 114
017029 1329 33 0 740 0 159 0 21156 0 0
017034 74 4 0 0 38 0 4 0 1935 4
017035 179 4 0 0 12 0 4 0 0 5416
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 3) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2020 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################# Filtro #########################################
### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value < 0) %>% 

#p <- data.frame(ZM = ZM_CF,
 #               filtro_municipio = filtro_mig)

#write.table(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intramunicipal.txt"), col.names = TRUE)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intramunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intramunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

################################################################################
tabla1 <- lapply(1:length(ZM), function(x){
                                filtro  <- Inmigrantes[[x]] %>%
                                            full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                              filter(value < filtro_mig[x]) %>% 
                                               pull(rn)
                                 Migrantes %>%
                                  as.data.frame() %>%
                                   tibble::rownames_to_column(var = "rn") %>% 
                                    melt(., id.vars = "rn", variable.name = "cn") %>%
                                     mutate_if(is.factor, as.character) %>%
                                      filter(.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]) %>%
                                       mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]), value, 0)) %>% 
                                        mutate(rn = ifelse(.$rn %in% filtro, 
                                                           stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios (", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 100), 
                                                           substr(.$rn, 2, nchar(.$rn))),
                                               cn = ifelse(.$cn %in% filtro, 
                                                           stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios (", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 100), 
                                                           substr(.$cn, 2, nchar(.$cn)))) %>%
                                         filter(value > 0) %>%
                                          dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                           column_to_rownames(., var = "rn")
})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                                             tabla1[[i]] %>%
#                                              as.data.frame() %>%
#                                               adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/50) %>%
#                                                    pull(Total)
#})

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intramunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intramunicipal.RDS"))

total_tablas <- totales(tabla1, ZM)
porcentajes_tablas <- porcentajes(tabla1, ZM)

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, totales[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel intramunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intramunicipal.RDS"))

#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1, ZM_CF = ZM_CF, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (Intramunicipal).pdf"
 
## Gráficos a nivel municipal 
chord_diagram_graph(file = file, 
                    width = 15,
                    height = 10,
                    family = "Montserrat Medium",
                    paleta = paleta,
                    ZM_CF = ZM_CF,
                    tabla1,
                    tabla2,
                    color_labels = "#000C7D",
                    margin = c(0, 0, 0, 0))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZM a nivel intramunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     ZM_CF , 
                     tabla1, 
                     NOM_ZM_CF)

Gráfico Sankey

## Tomamos las Zonas Metropolitanas con más de 3 municipios con flujos migratorios 
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 2) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") 

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                   ZM <- ZM_2020 %>%
                                          select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                           filter(CVE_ZM %in% ZM_CF[x])  %>%
                                            mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                             pull(NOM_MUN)
                                    tabla %>%
                                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                                      filter(value > 0) 
  }
)
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 9, family = "montserrat"),
                                   legend.position = c(1, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.35)) +
                        scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst desagregado por ZM_Absolutos (Intramunicipal).pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 13000) %>% 
               pull(rn)

################################################################################
tabla1 <- Migrantes %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
               filter(.$rn %in% ZM | .$cn %in% ZM) %>%
                mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
                 mutate(rn = ifelse(.$rn %in% filtro, 
                                    stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios (", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 30), 
                                    substr(.$rn, 2, nchar(.$rn))),
                        cn = ifelse(.$cn %in% filtro, 
                                    stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios (", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 30), 
                                    substr(.$cn, 2, nchar(.$cn)))) %>%
                  filter(value > 0) %>%
                   dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                    column_to_rownames(., var = "rn")
# Paleta de colores
groupColors <- paste0(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))), "7F")

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM (Intramunicipal).pdf"),
          width = 7, height = 7, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)

circos.clear()
circos.par(start.degree = 90, 
           clock.wise = TRUE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(1.5, 4))

# Paleta de colores
groupColors <- setNames(rev(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1)))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 0.2, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(7),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(5),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

dev.off()
paleta[1]
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 13000) %>% 
               pull(rn)
################################################################################
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(.$rn %in% ZM | .$cn %in% ZM) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
                mutate(rn = case_when(.$rn %in% filtro ~ stringr::str_wrap(paste(substr(as.character(.$rn), 2, 3), "Otros municipios (", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 30), 
                                     .$rn %nin% filtro ~ substr(.$rn, 2, nchar(.$rn))),
                       cn = case_when(.$cn %in% filtro ~ stringr::str_wrap(paste(substr(as.character(.$cn), 2, 3), "Otros municipios (", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 30),  
                                      .$cn %nin% filtro ~substr(.$cn, 2, nchar(.$cn)))) %>%
                 filter(value > 0) 

tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()

# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de movilidad laboral para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
          ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst de ZMVM a nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
# Paleta de colores
groupColors <- paste0(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))), "7F")

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM_grupos (Intramunicipal).pdf"),
          width = 10, height = 10, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)
 
circos.clear()
circos.par(start.degree = 90, 
           clock.wise = TRUE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(0, 4))

# Paleta de colores
groupColors <- setNames(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 1, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(9),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(7),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

highlight.sector(grupo1, 
                 track.index = 1, 
                 col = groupColors[1], 
                 text = "Ciudad de México", 
                 cex = 1.5, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), niceFacing = TRUE)

highlight.sector(grupo2, 
                 track.index = 1, 
                 col = groupColors[15], 
                 text = "México", 
                 cex = 1.5, 
                 text.col = "white",
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

highlight.sector(grupo3, 
                 track.index = 1, 
                 col = groupColors[20], 
                 text = "Hidalgo", 
                 cex = 1, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)
dev.off()
paleta[1]

Etiquetas

etiquetas  <- lapply(1, function(x){
                        orden <- str_sort(unique(c(colnames(tabla1), rownames(tabla1))), numeric = TRUE)
                        p <-  tabla1 %>% 
                               as.data.frame() %>%
                                tibble::rownames_to_column(var = "rn") %>%
                                 melt(., id.vars = "rn", variable.name = "cn") %>%
                                  as.data.frame() %>% 
                                   mutate(rn = str_wrap(.$rn, 100),
                                          cn = str_wrap(.$cn, 100)) %>%
                                    ggplot() + 
                                     geom_bar(aes(x = as.character(value, orden), fill = rn))  + 
                                      geom_bar(aes(x = as.character(value, orden), fill = cn))  + 
                                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                                             text = element_text(family = "Montserrat Medium"),
                                             axis.text = element_blank(),
                                             axis.title = element_blank(),
                                             strip.text = element_text(size = 9, face = "bold", family = "Montserrat Medium"),  
                                             legend.key.size = unit(0.4, "cm"), 
                                             legend.spacing.y = unit(0.4, "cm"),
                                             legend.text = element_text(size = 7, family = "Montserrat Medium"),
                                             legend.title = element_text(size = 8 , family = "Montserrat Medium")) + 
                                       scale_fill_manual(values = colorRampPalette(paleta)(max(ncol(tabla1), nrow(tabla1)))) + 
                                         guides(fill = guide_legend(ncol = 1)) + 
                                        guides(fill = guide_legend(ncol = 1)) + 
                                         labs(fill = "ZM del Valle de México",
                                          color = "ZM del Valle de México")
                         leg <- get_legend(p)
                         as_ggplot(leg)
 })

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZMVM a nivel intramunicipal.pdf"), 
          width = 7, height = 8, 
          fallback_resolution = 400,
          family = "montserrat", onefile = TRUE)
for(i in 1){
  print(etiquetas[i])
}
dev.off()
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                      group_by(rn) %>% 
                       summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(value < 30000) %>% 
               pull(rn)
#########################################################################################

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = ifelse(.$rn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 50), .$rn),
                      cn = ifelse(.$cn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 50) , .$cn)) %>%
                filter(value > 0) 

p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.7,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst de la ZMVM (Intramunicipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar 
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intramunicipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intramunicipal).RData"))
Indicadores de Movilidad estudiantil
Zonas Metropolitanas
Clave del municipio Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 901 262 274 602 1 945 9 301 −7 356 11 246 0.42 2.0 −1.6 −18 602
001002 51 474 48 275 13 095 0 0 0 0 0.00 0.0 0.0 0
001003 58 155 55 019 13 315 0 0 0 0 0.00 0.0 0.0 0
001004 16 997 15 959 4 370 0 0 0 0 0.00 0.0 0.0 0
001005 129 859 122 544 29 323 7 414 1 797 5 617 9 211 11.75 2.8 8.9 −3 594
001006 47 557 44 893 11 641 0 0 0 0 0.00 0.0 0.0 0
001007 57 269 53 484 15 896 0 0 0 0 0.00 0.0 0.0 0
001008 9 552 8 868 2 489 0 0 0 0 0.00 0.0 0.0 0
001009 22 461 21 182 5 605 0 0 0 0 0.00 0.0 0.0 0
001010 20 382 18 987 5 129 0 0 0 0 0.00 0.0 0.0 0
001011 61 986 57 999 14 930 2 593 854 1 739 3 447 8.64 2.8 5.8 −1 708
002001 440 624 422 238 112 987 0 0 0 0 0.00 0.0 0.0 0
002002 1 042 395 1 004 592 266 099 0 0 0 0 0.00 0.0 0.0 0
002003 102 896 98 206 24 958 0 0 0 0 0.00 0.0 0.0 0
002004 1 910 568 1 829 472 459 410 1 321 1 909 −588 3 230 0.14 0.2 −0.1 −3 818
002005 126 264 121 701 27 084 1 909 1 321 588 3 230 3.08 2.1 0.9 −2 642
002006 117 050 109 811 28 950 0 0 0 0 0.00 0.0 0.0 0
003001 72 358 69 371 19 295 0 0 0 0 0.00 0.0 0.0 0
003002 62 884 59 781 14 139 0 0 0 0 0.00 0.0 0.0 0
003003 290 063 279 213 75 849 0 0 0 0 0.00 0.0 0.0 0
Fuente: Estimaciones del CONAPO.

Migración intermunicipal

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2020 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios & .$I_ZM %in% "No pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_intermunicipal.RDS"))

Matrices

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_intermunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 17)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intermunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil hace 3 años a nivel municipal, 2015 - 2020

Matriz de movilidad estudiantil por zonas metropolitanas
Nivel intermunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 0 37 0 0 0 122 101 12 0 240 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 662 0 0 0 0 22 272 0 0 67 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 509 0 0 0 0 0 0 0 0 21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 128 3 0 0 2 24 319 0 0 3 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 0 36 45 0 0 121 88 0 0 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 706 0 24 0 96 0 510 95 10 0 163 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 559 0 0 32 9 312 0 8 22 0 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 74 0 0 0 0 70 38 0 0 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 158 27 4 0 0 173 264 0 0 3 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 176 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 0 3 0 0 0 233 196 0 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 0 148 0 262 80 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 16 0 76 42 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 40 119 0 1035 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 251 81 1979 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 80 25 78 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003001 8 0 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 0 43 0 7 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 260 13 0 0 0 0 0 31 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 40 0 0 0 0 0 0 0 146 20 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 55 0 0 0 284 0 0 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 8 0 0 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 298 36 23 195 18 0 45
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 102 0 0 38 37 0 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 65 0 11 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 343 37 0 0 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 366 489 5 0 0 14 0 26
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 263 0 0 0 0 0 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 11 0 0 0 0 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 37 227 2 0 44 0 0 0
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 162 45 27 0 0 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 0) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2020 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})
################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0) %>%
#p <- data.frame(ZM = ZM_CF,
#                filtro_municipio = tabla_municipios,
#                filtro_estado = tabla_estados)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intermunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
tabla1 <- lapply(1:length(ZM_CF), function(x){
                                    # filtro de municipios de la ZM
                                      filtro  <- Inmigrantes[[x]] %>%
                                                  full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                                    mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                                      filter(value > filtro_mig[x]) %>%   ## Cambia el filtro de los municipios de la Zonas Metropolitanas
                                                       pull(rn)
                                      
                                     
                                    # filtro de estados
                                     filtro_est <- Inmigrantes[[x]] %>%
                                                    full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                                     filter(rn %nin% ZM[[x]]) %>%
                                                      mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                                       mutate(rn = substr(.$rn, 1, 3)) %>%
                                                        group_by(rn) %>%
                                                         summarise(value = sum(value)) %>%
                                                          filter(value >= filtro_out[x]) %>% 
                                                           pull(rn)
                                     
                                     Migrantes %>%
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "rn") %>% 
                                        melt(., id.vars = "rn", variable.name = "cn") %>%
                                         mutate_if(is.factor, as.character) %>%
                                          filter(.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]) %>%
                                           mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]), value, 0)) %>% 
                                            mutate(rn = case_when(.$rn %in% ZM[[x]] & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                                                  .$rn %in% ZM[[x]] & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZM"), 100),
                                                                  .$rn %nin% ZM[[x]] & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 100),
                                                                  .$rn %nin% ZM[[x]] & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                                                   cn = case_when(.$cn %in% ZM[[x]] & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                                                  .$cn %in% ZM[[x]] & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZM"), 100),
                                                                  .$cn %nin% ZM[[x]] & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 100),
                                                                  .$cn %nin% ZM[[x]] & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                                            filter(value > 0) %>%
                                             dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                              column_to_rownames(., var = "rn") 
  }
)

################################################################################
## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:length(ZM_CF), function(i){
#                                           tabla1[[i]] %>%
#                                            as.data.frame() %>%
#                                             adorn_totals(c("row", "col"), 
#                                                           fill = "-", 
#                                                            na.rm = TRUE, 
#                                                             ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                              select(`Otros estados`) %>%
#                                               slice(nrow(.)) %>%
#                                                mutate(`Otros estados` = .$`Otros estados`/10) %>%
#                                                 pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                              p <- tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      slice(-nrow(.))
#                              if(sum(p) == 0) {
#                                return(0)
#                              } else {
#                                p %>% 
#                                 adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/100) %>%
#                                                    pull(Total)
#                              }
#                                           })


## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 0.
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intermunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intermunicipal.RDS"))

total_tablas <- totales(tabla1, ZM)
porcentajes_tablas <- porcentajes(tabla1, ZM)

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, totales[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intermunicipal.RDS"))

#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1, ZM_CF = ZM_CF, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (Intermunicipal).pdf"
 
## Gráficos a nivel municipal 
chord_diagram_graph(file = file, 
                    width = 15,
                    height = 10,
                    family = "Montserrat Medium",
                    paleta = paleta,
                    ZM_CF = ZM_CF,
                    tabla1,
                    tabla2,
                    color_labels = "#000C7D",
                    margin = c(0, 0, 0, 0))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZM a nivel intermunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     ZM_CF , 
                     tabla1, 
                     NOM_ZM_CF)

Gráfico Sankey

## Tomamos las Zonas Metropolitanas con más de 3 municipios con flujos migratorios 
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 2) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character)
             

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                   ZM <- ZM_2020 %>%
                                          select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                           filter(CVE_ZM %in% ZM_CF[x])  %>%
                                            mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                             pull(NOM_MUN)
                                    tabla %>%
                                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                                      mutate(rn = case_when(.$rn %in% ZM ~ .$rn,
                                                            .$rn %nin% ZM ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))])),
                                             cn = case_when(.$cn %in% ZM ~ .$cn,
                                                            .$cn %nin% ZM ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]))) %>%
                                       filter(value > 0) 
  }
) 
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
              ggplot(aes(axis1 = rn, 
                          axis2 = cn, 
                           y = value),  # c("value", "freq", "tasa")
                      reverse = FALSE, 
                       na.rm = TRUE) +
               geom_alluvium(aes(fill = rn),
                              curve_type = "quintic", 
                               color = "transparent", 
                                alpha = 0.85, 
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                geom_stratum(aes(fill = cn), 
                              color = "white", 
                               alpha = 0.65,  
                                lwd = 0.001, 
                                 width = 1/5,
                                  reverse = FALSE) +
                  geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                   stat = "stratum", 
                                    size = 3, 
                                     direction = "y", 
                                      nudge_x = -.2,
                                       min.segment.length = unit(1, "lines"),
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3,
                                      direction = "y", 
                                       nudge_x = .2, 
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 9, family = "montserrat"),
                                   legend.position = c(1, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.35)) +
                        scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst desagregado por ZM_Absolutos (Intermunicipal).pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             filter(rn %in% ZM) %>%
              mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
               filter(value > 500) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 500) %>%
                      pull(rn)

################################################################################
tabla1 <- Migrantes %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
              filter(.$rn %in% ZM | .$cn %in% ZM) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM| .$cn %in% ZM), value, 0)) %>% 
                mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                      .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZMVM"), 100),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 100),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                       cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                      .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZMVM"), 100),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 100),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                 filter(value > 0) %>%
                  dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                   column_to_rownames(., var = "rn") 
# Grupo de colores
groupColors <- paste0(rev(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1)))))), "7F")

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM (Intermunicipal).pdf"),
          width = 7, height = 7, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)

circos.clear()
circos.par(start.degree = 90, 
           clock.wise = TRUE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(1.5, 4))

# Paleta de colores
groupColors <- setNames(rev(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1)))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 0.2, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(7),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(5),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

dev.off()
paleta[1]
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             filter(rn %in% ZM) %>%
              mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
               filter(value > 500) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 500) %>%
                      pull(rn)

################################################################################
tabla <- Migrantes %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
              filter(.$rn %in% ZM | .$cn %in% ZM) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM| .$cn %in% ZM), value, 0)) %>% 
                mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                      .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(substr(estados[as.numeric(substr(.$rn, 1, 3))], 2, 3), "ZMVM"), 100),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 100),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                       cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                      .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(substr(estados[as.numeric(substr(.$cn, 1, 3))], 2, 3), "ZMVM"), 100),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 100),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                 filter(value > 0)  

tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()

# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

# Grupo 4
grupo4 <- tabla %>%
           filter(substr(.$rn, 1, 2) %nin% c("09", "15", "13")) %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de movilidad laboral para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
          ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst de ZMVM a nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
# Paleta de colores
groupColors <- paste0(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))), "7F")

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM_grupos (Intermunicipal).pdf"),
          width = 10, height = 10, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)
 
circos.clear()
circos.par(start.degree = 90, 
           clock.wise = FALSE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(0, 4))

# Paleta de colores
groupColors <- setNames(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 1, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(9),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(7),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

highlight.sector(grupo1, 
                 track.index = 1, 
                 col = groupColors[1], 
                 text = "Ciudad de México", 
                 cex = 1.5, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), niceFacing = TRUE)

highlight.sector(grupo2, 
                 track.index = 1, 
                 col = groupColors[15], 
                 text = "México", 
                 cex = 1.5, 
                 text.col = "white",
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

highlight.sector(grupo3, 
                 track.index = 1, 
                 col = groupColors[20], 
                 text = "Hidalgo", 
                 cex = 1, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

highlight.sector(grupo4, 
                 track.index = 1, 
                 col = groupColors[30], 
                 text = "Otro municipios", 
                 cex = 1.5, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

dev.off()
paleta[1]

Etiquetas

etiquetas  <- lapply(1, function(x){
                        orden <- str_sort(unique(c(colnames(tabla1), rownames(tabla1))), numeric = TRUE)
                        p <-  tabla1 %>% 
                               as.data.frame() %>%
                                tibble::rownames_to_column(var = "rn") %>%
                                 melt(., id.vars = "rn", variable.name = "cn") %>%
                                  as.data.frame() %>% 
                                   mutate(rn = str_wrap(.$rn, 100),
                                          cn = str_wrap(.$cn, 100)) %>%
                                    ggplot() + 
                                     geom_bar(aes(x = as.character(value, orden), fill = rn))  + 
                                      geom_bar(aes(x = as.character(value, orden), fill = cn))  + 
                                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                                             text = element_text(family = "Montserrat Medium"),
                                             axis.text = element_blank(),
                                             axis.title = element_blank(),
                                             strip.text = element_text(size = 9, face = "bold", family = "Montserrat Medium"),  
                                             legend.key.size = unit(0.4, "cm"), 
                                             legend.spacing.y = unit(0.4, "cm"),
                                             legend.text = element_text(size = 7, family = "Montserrat Medium"),
                                             legend.title = element_text(size = 8 , family = "Montserrat Medium")) + 
                                       scale_fill_manual(values = colorRampPalette(paleta)(max(ncol(tabla1), nrow(tabla1)))) + 
                                         guides(fill = guide_legend(ncol = 1)) + 
                                        guides(fill = guide_legend(ncol = 1)) + 
                                         labs(fill = "ZM del Valle de México",
                                          color = "ZM del Valle de México")
                         leg <- get_legend(p)
                         as_ggplot(leg)
 })

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZMVM a nivel intermunicipal.pdf"),
          width = 7, height = 9, 
          fallback_resolution = 400,
          family = "montserrat", onefile = TRUE)
for(i in 1){
  print(etiquetas[i])
}
dev.off()
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN, by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN, by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                      group_by(rn) %>% 
                       summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(rn %in% ZM) %>%
               filter(value > 30000) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 500) %>%
                      pull(rn)
#########################################################################################

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ .$rn,
                                     .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZMVM"), 20),
                                     .$rn %nin% ZM & .$rn %nin% filtro & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 20),
                                     .$rn %nin% ZM & .$rn %nin% filtro & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                       
                      cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ .$cn,
                                     .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZMVM"), 20),
                                     .$cn %nin% ZM & .$cn %nin% filtro & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 20),
                                     .$cn %nin% ZM & .$cn %nin% filtro & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                filter(value > 0) 


p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.85,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst de la ZMVM (Intermunicipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar v
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intermunicipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intermunicipal).RData"))
Indicadores de Movilidad estudiantil
Zonas Metropolitanas
Clave del municipio Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 901 262 0 1 194 6 832 −5 638 8 026 0.26 1.480 −1.2 −13 664
001002 51 474 48 275 0 1 173 493 680 1 666 4.70 1.977 2.7 −986
001003 58 155 55 019 0 567 119 448 686 2.00 0.421 1.6 −238
001004 16 997 15 959 0 516 209 307 725 6.26 2.537 3.7 −418
001005 129 859 122 544 0 416 118 298 534 0.66 0.187 0.5 −236
001006 47 557 44 893 0 1 630 1 084 546 2 714 7.05 4.690 2.4 −2 168
001007 57 269 53 484 0 990 2 295 −1 305 3 285 3.58 8.289 −4.7 −4 590
001008 9 552 8 868 0 196 118 78 314 4.26 2.562 1.7 −236
001009 22 461 21 182 0 644 35 609 679 5.90 0.321 5.6 −70
001010 20 382 18 987 0 193 465 −272 658 1.96 4.725 −2.8 −930
001011 61 986 57 999 0 482 207 275 689 1.61 0.690 0.9 −414
002001 440 624 422 238 0 638 857 −219 1 495 0.30 0.397 −0.1 −1 714
002002 1 042 395 1 004 592 0 596 870 −274 1 466 0.12 0.170 −0.1 −1 740
002003 102 896 98 206 0 1 260 2 136 −876 3 396 2.51 4.249 −1.7 −4 272
002004 1 910 568 1 829 472 0 2 717 1 559 1 158 4 276 0.29 0.167 0.1 −3 118
002005 126 264 121 701 0 183 80 103 263 0.30 0.129 0.2 −160
002006 117 050 109 811 0 0 0 0 0 0 0 0 0
003001 72 358 69 371 0 75 5 70 80 0.21 0.014 0.2 −10
003002 62 884 59 781 0 316 7 309 323 1.03 0.023 1.0 −14
003003 290 063 279 213 0 462 495 −33 957 0.32 0.348 0.0 −990
Fuente: Estimaciones del CONAPO.

Movilidad metropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2020 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios) %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_metropolitana.RDS"))

Matrices

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_metropolitana.RDS"))

Migrantes <- svytable(~CVE_ZM_ASI + CVE_ZM, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_ZM, CVE_ZM_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_ZM" = "row_labels") %>% 
                  arrange(CVE_ZM) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_ZM = substr(.$CVE_ZM, 8, 12)) %>% 
              pull(CVE_ZM)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_ZM" = ".") %>%
                mutate(`CVE_ZM` = substr(.$CVE_ZM, 12, 17)) %>%
                 pull(CVE_ZM)

# Se elimina la variable CVE_ZM
Migrantes <- Migrantes %>%
              select(-CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Metropolitano")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_ZM"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2020.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil hace 5 años a nivel municipal, 2015 - 2020

Matriz de movilidad estudiantil por zonas metropolitanas
Nivel municipal
CVE_ZM 01.01 02.01 02.02 02.03 03.01 03.02 04.01 05.01 05.02 05.03 05.04 05.05 06.01 06.02 07.01 07.02 08.01 08.02 08.03 08.04 09.01 10.01 11.01 11.02 11.03 11.04 11.06 11.07 12.01
01.01 330807 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 79 0 0 79 132 0 0 0 59
02.01 0 112987 148 342 0 0 0 0 0 0 0 0 0 0 0 0 0 27 0 0 0 0 0 0 0 0 0 0 0
02.02 0 16 266099 42 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
02.03 0 331 106 489724 0 0 0 0 0 0 0 0 0 0 0 0 79 0 0 0 0 0 0 0 0 0 79 0 0
03.01 0 40 0 0 75849 146 0 0 0 0 0 0 0 0 0 7 0 0 0 0 0 21 0 0 0 0 0 0 0
03.02 0 0 0 55 284 92491 0 0 0 0 0 0 0 0 0 0 0 0 0 0 48 0 0 0 0 0 0 0 0
04.01 0 0 0 0 0 0 79728 0 0 0 0 0 0 0 0 0 0 0 0 0 25 0 0 0 0 0 0 0 0
05.01 21 0 0 0 0 0 0 348180 22 0 78 0 0 0 0 0 0 0 0 0 0 381 0 0 67 0 0 0 0
05.02 0 0 0 0 0 0 0 33 95197 8 157 0 0 0 0 0 0 0 0 0 0 12 0 12 0 0 0 0 0
05.03 0 0 0 0 0 0 0 0 3 48571 34 6 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0
05.04 0 0 0 0 0 0 0 112 0 0 272903 0 0 0 0 0 0 0 0 0 5 0 0 16 0 0 0 0 0
05.05 0 0 0 0 0 0 0 0 23 50 49 24555 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
06.01 0 0 0 24 0 0 0 0 0 0 0 0 87818 190 0 0 0 0 0 0 100 0 0 24 0 0 0 0 0
06.02 0 0 0 0 0 0 0 0 0 0 0 0 715 34841 0 0 0 0 0 0 12 0 0 0 0 0 0 0 0
07.01 16 0 0 0 0 0 0 0 0 0 2 0 0 0 102068 170 0 0 0 0 0 0 0 0 0 0 0 0 0
07.02 0 0 0 0 0 0 0 0 0 0 0 0 0 0 65 226417 0 0 0 0 144 0 0 0 0 0 0 0 9
08.01 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 282455 0 0 138 0 0 0 0 0 0 0 0 0
08.02 0 0 0 0 0 0 0 18 0 0 0 0 0 0 0 0 1144 53425 11 0 0 0 0 0 0 0 0 0 0
08.03 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18 18 32027 0 0 0 0 0 0 0 0 0 0
08.04 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 399731 0 0 0 0 0 0 0 0 0
09.01 7 0 26 4 44 0 0 0 0 0 0 0 0 0 0 4 37 0 0 69 5164297 29 0 33 28 0 0 0 66
10.01 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 204068 0 42 0 0 0 0 0
11.01 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28 174058 317 119 0 147 0 0
11.02 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45 52061 675 0 293 210 0
11.03 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 0 0 0 0 0 10 665 497020 0 300 1463 0
11.04 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 79 79 87 29005 23 0 0
11.06 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 56 473 484 0 149649 80 0
11.07 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 34 0 21 835 2001 0 310 69321 0
12.01 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 66 0 0 0 48 0 0 0 204590
12.02 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 295 0 0 0 0 0 0 0 332
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

################################################################################
tabla1 <- lapply(1, function(x){
                         Migrantes %>%
                          as.data.frame() %>%
                           tibble::rownames_to_column(var = "rn") %>% 
                            melt(., id.vars = "rn", variable.name = "cn") %>%
                             mutate_if(is.factor, as.character) %>%
                              mutate(value = ifelse((.$rn != .$cn), value, 0)) %>% 
                               filter(value > 0) %>%
                                dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                 column_to_rownames(., var = "rn") 
}
)
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1, ZM_CF = 1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (metropolitano).pdf"
 
## Gráficos a nivel municipal 
chord_diagram_graph(file = file, 
                    width = 15,
                    height = 10,
                    family = "Montserrat Medium",
                    paleta = paleta,
                    ZM_CF = 1,
                    tabla1,
                    tabla2,
                    color_labels = "#000C7D",
                    margin = c(0, 0, 0, 0))
Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
ZM <- ZM_2020 %>% 
       select(CVE_ZM, NOM_ZM) %>% 
        distinct(CVE_ZM, NOM_ZM) %>%
         mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
          pull(CVE_ZM)

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)
################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
#p <- data.frame(ZM = ZM,
 #               filtro_zm = filtro_mig)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel metropolitano.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel metropolitano.xlsx"), colNames = TRUE) %>%
               pull(filtro_zm)

################################################################################
tabla1 <- lapply(1:length(ZM), function(x){
                                # filtro de estados
                                  filtro_zm <- Inmigrantes[[x]] %>%
                                                full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                                 filter(rn %nin% ZM[[x]]) %>%
                                                  mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                                   mutate(rn = substr(.$rn, 1, 5)) %>%
                                                    group_by(rn) %>%
                                                     summarise(value = sum(value)) %>%
                                                      filter(value >= filtro_mig[x]) %>% 
                                                       pull(rn)
                                Migrantes %>%
                                 as.data.frame() %>%
                                  tibble::rownames_to_column(var = "rn") %>% 
                                   melt(., id.vars = "rn", variable.name = "cn") %>%
                                    mutate_if(is.factor, as.character) %>%
                                     filter(.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]) %>%
                                       mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]), value, 0)) %>% 
                                         mutate(rn = case_when(.$rn %in% ZM[[x]] ~ .$rn,
                                                               .$rn %nin% ZM[[x]] & substr(.$rn, 1, 5) %in% filtro_zm ~ .$rn,
                                                               .$rn %nin% ZM[[x]] & substr(.$rn, 1, 5) %nin% filtro_zm ~ "Otras zonas metropolitanas"),
                                                 
                                               cn = case_when(.$cn %in% ZM[[x]] ~ .$cn,
                                                               .$cn %nin% ZM[[x]] & substr(.$cn, 1, 5) %in% filtro_zm ~ .$cn,
                                                               .$cn %nin% ZM[[x]] & substr(.$cn, 1, 5) %nin% filtro_zm ~ "Otras zonas metropolitanas")) %>%
                                         filter(value > 0) %>%
                                          dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                           column_to_rownames(., var = "rn") 
  }
)

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, zm[i])
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano_Reduccion.xlsx"), 
               overwrite = TRUE)
}
saveRDS(tabla1, paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano.RDS"))

total_tablas <- totales(tabla1, ZM)
porcentajes_tablas <- porcentajes(tabla1, ZM)

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, totales[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano.RDS"))

#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1, ZM_CF = ZM_CF, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (metropolitano)_individual.pdf"
 
## Gráficos a nivel municipal 
chord_diagram_graph(file = file, 
                    width = 8,
                    height = 8,
                    family = "Montserrat Medium",
                    paleta = paleta,
                    ZM_CF = ZM_CF,
                    tabla1,
                    tabla2,
                    color_labels = "#000C7D",
                    margin = c(0, 0, 0, 0))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZM a nivel metropolitano.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     ZM_CF , 
                     tabla1, 
                     NOM_ZM_CF)

Referencias

Librerias que se usaron en el documento